package com.ruoyi.pos.api.utils;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.AuditStatusEnum;
import com.ruoyi.common.enums.YesOrNoEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.Fun;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.pos.web.domain.TStatisticInfo;
import com.ruoyi.pos.web.domain.TUserDefaultInfo;
import com.ruoyi.pos.web.domain.TUserInfo;
import com.ruoyi.pos.web.domain.TUserTeamInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author luobo
 * @Date 2021/9/17 15:31
 */
@Component
public class CommonUtils {
    @Autowired
    private Environment env;
    @Autowired
    private RedisCache redisCache;
    @Value("${user.token}")
    private String tokenUrl; //token key
    @Value("${user.tokenFailure}")
    private String tokenFailure; //token失效时间

    /**
     * 获取请求token对应的userId
     * @return userId
     */
    public String getUserId() {
        Map<String, String> map = new HashMap<String, String>();
        String token = getToken();
        Object userId = redisCache.getCacheObject(tokenUrl + ":" + token);
        if (null == userId) {
            return null;
        }
        return userId.toString();
    }

    /**
     * 获取请求token和userId
     * @return token和userId
     */
    public JSONObject getTokenAndUserId() {
        JSONObject jo = new JSONObject();
        String token = getToken();
        Object userId = redisCache.getCacheObject(tokenUrl + ":" + token);
        if (null == userId) {
            return null;
        }
        jo.put("userId", userId.toString());
        jo.put("token", token);
        return jo;
    }

    /**
     * 获取HttpServletRequest
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequestsSafely() {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            return requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 请求中获取 token
     * @return token
     */
    public String getToken() {
        HttpServletRequest request = getRequestsSafely();
        if (request != null) {
            String token = request.getHeader("token");
            if (token != null)
                return token;
            Cookie[] cookies = request.getCookies();
            if (null != cookies) {
                for (int i = 0; i < cookies.length; i++) {
                    Cookie cookie = cookies[i];
                    if ("token".equals(cookie.getName())) {
                        return cookie.getValue();
                    }
                }
            }
            String param = request.getQueryString();
            Map<String, Object> dataMap = Fun.paramsToMap(param);
            if (dataMap.get("token") != null) {
                return dataMap.get("token").toString();
            }
        }
        return "";
    }
    //初始化统计表数据
    public TStatisticInfo generateStatisticInfo(TUserInfo user, Date date, String brandId) {
        TStatisticInfo statistic = TStatisticInfo.Builder.getInstance()
                .withId(IdUtils.simpleUUID())
                .withCreateTime(date)
                .withUserId(user.getUserId())
                .withBrandId(brandId) //品牌id
                .withMyTransMoney(BigDecimal.ZERO) //我的交易总额
                .withMyTransNum(BigDecimal.ZERO) //我的交易笔数
                .withMyTerminalNum(BigDecimal.ZERO) //我的终端数
                .withMyPartnerNum(BigDecimal.ZERO) //我的伙伴数
                .withMyBuyTerminalNum(BigDecimal.ZERO) //我的购买终端数
                .withMyExchangelTerminalNum(BigDecimal.ZERO) //我的兑换终端数
                .withMyOutTerminalNum(BigDecimal.ZERO) //我的划出终端数
                .withMyInTerminalNum(BigDecimal.ZERO) //我的划入终端数
                .build();
        return statistic;
    }
    //初始化本地交易流水表数据
    public TUserDefaultInfo generateTUserDefaultInfo(String userId,
                                                     String brandId,
                                                     String transType,
                                                     String transOperType,
                                                     BigDecimal transAmount,
                                                     String orderId,
                                                     String subUserId,
                                                     Long serialId,
                                                     String snCode,
                                                     BigDecimal otherTransAmount){
        TUserDefaultInfo defaultInfo = TUserDefaultInfo.Builder.getInstance()
                .withId(IdUtils.simpleUUID())
                .withUserId(userId)
                .withCreateTime(DateUtils.getNowDate())
                .withBrandId(brandId)
                .withTransType(transType)
                .withTransOperType(transOperType)
                .withTransAmount(transAmount)
                .withOrderId(orderId)
                .withSubUserId(subUserId)
                .withSerialId(serialId)
                .withSnCode(snCode)
                .withOtherTransAmount(otherTransAmount)
                .withWithdrawAmount(BigDecimal.ZERO) //提现实际到账金额
                .withServiceChargeAmount(BigDecimal.ZERO) //提现手续费
                .build();
        return defaultInfo;
    }
    //初始化用户信息
    public TUserInfo generateTUserInfo(Date date){
        TUserInfo user = TUserInfo.Builder.getInstance()
                .withUserId(IdUtils.simpleUUID())
                .withCreateTime(date)
                .withRegistreTime(date)
                .withUserStatus(YesOrNoEnums.YES.getCode())
                .withAuditStatus(AuditStatusEnum.WAIT_AUDIT.getCode())
                .withToken(IdUtils.simpleUUID())
                .withInviteCode(System.currentTimeMillis() + "")
                .withBalanceSum(BigDecimal.ZERO) //总余额
                .withBalanceWithdraw(BigDecimal.ZERO) //已提现余额
                .withBalanceUse(BigDecimal.ZERO) //已使用余额
                .withGoldSum(BigDecimal.ZERO) //总金币
                .withGoldWithdraw(BigDecimal.ZERO) //已提现金币
                .withGoldExchange(BigDecimal.ZERO) //已兑换金币
                .withIntegralSum(BigDecimal.ZERO) //总积分
                .withIntegralExchange(BigDecimal.ZERO) //已兑换积分
                .withDealGoldMark(BigDecimal.ZERO) //总交易金
                .withDealGoldExchangeMark(BigDecimal.ZERO) //已兑换交易金
                .withDealGold(BigDecimal.ZERO) //已兑现奖励金
                .withAwardGoldMark(BigDecimal.ZERO) //总奖励金
                .withAwardGoldExchangeMark(BigDecimal.ZERO) //已兑换奖励金
                .withAwardGold(BigDecimal.ZERO) //已兑现交易金
                .withDealAmountHasSend(BigDecimal.ZERO) //已发放交易金序号的金额
                .withAwardAmountHasSend(BigDecimal.ZERO) //已发放奖励金序号的金额
                .withAutonymType(YesOrNoEnums.NO.getCode()) //实名认证状态
                .withTotalTransAmount(BigDecimal.ZERO) //用户累计交易额
                .withSignStatus(AuditStatusEnum.WAIT_AUDIT.getCode())
                .build();
        return user;
    }
    //初始化用户团队信息
    public TUserTeamInfo generateUserTeamInfo(String userId, String subUserId, String teamType, Date date){
        TUserTeamInfo team = TUserTeamInfo.Builder.getInstance()
                .withId(IdUtils.simpleUUID())
                .withUserId(userId)
                .withSubUserId(subUserId)
                .withTeamType(teamType)
                .withCreateTime(date)
                .build();
        return team;
    }
}
